extern "C"
{
	#include <curses.h>
}
#include "FengGo.hpp"
	
/*显示棋盘
*输入：iFlag 0-棋手落子
*            1-FengGo落子
*            2-已落子
*            9-无效输入
*/
int showBoard(int iFlag);

//计算机计算落子
int toAI();

int main(int argc, char *argv[])
{
	int iSitFlag = 3; //落子标志  0-落子成功  2-此处已有子（随便定义一个数，防止程序出错）
	int iBoard;   //行棋方标志  0-棋手落子  1-FengGo落子
	
	initscr();
	cbreak();
	crmode();
	nl();
	echo();
	intrflush(stdscr,FALSE);
	keypad(stdscr,TRUE);
	refresh();
	
	//第一次显示棋盘
	showBoard(0);
	refresh();
	
	iBoard = 0;   //第一次棋手先走
	while(1){
		memset(sCols , 0x00, sizeof(sCols ));
		memset(sLines, 0x00, sizeof(sLines));
		scanw("%s %s",sCols, sLines);
		
		if(AIutil.strlwc(sCols[0]) == 'z'){
			endwin();
			break;
		}else if(!(AIutil.strlwc(sCols[0]) >= 'a' && AIutil.strlwc(sCols[0]) <= 's')){
			clear();
			showBoard(2);
			refresh();
			
		}else {
			if(iBoard == 0){
				//显示对弈者落子
				clear();
				iSitFlag = AIutil.sitting(sCols, sLines);
				showBoard(iSitFlag);
				if(iSitFlag == 0){
					iBoard = 1;
				}
				refresh();
			}
			if((iSitFlag == 0) && (iBoard == 1)){
				//显示计算机落子
				clear();
				iSitFlag = toAI();
				showBoard(iSitFlag);
				if(iSitFlag == 1){
					iBoard = 0;
				}
				refresh();
			}
		}
	}
	
	return 0;
}

int showBoard(int iFlag){
	int i, j;
	char sRow[59 + 1];
	char cFirstLine = 'A';  //列坐标
	
	//行坐标
	mvwprintw(stdscr,0,0,"   1  2  3  4  5  6  7  8  9  10 11 12 13 14 15 16 17 18 19");
	
	for(i = 0; i < BOARD_LINES; i++){
		memset(sRow, 0x20, sizeof(sRow));
		sRow[0] = cFirstLine++;
		sRow[sizeof(sRow) - 1] = 0;
		
		for(j = 0; j < BOARD_LINES; j++){
		
			switch((nowBoard[i] >> (j * 2)) & 0x0000000000000003){
				case 0 :
					sRow[j * 3 + 3] = '-';
					break;
				case 1 :
					sRow[j * 3 + 3] = '*';
					break;
				case 2 :
					sRow[j * 3 + 3] = '#';
					break;
			}
			
		}
		mvwprintw(stdscr,i + 1,0,"%s", sRow);
	}

	if(iFlag == 0 || iFlag == 1){
		mvwprintw(stdscr,i + 1,0,"Please enter your Lazi coordinates(Y X):");
		AIlog.boardHistory();
	}else if(iFlag == 2){
		mvwprintw(stdscr,i + 1,0,"Coordinate[%s][%s]already sitting(Y X):", sCols, sLines);
	}else if(iFlag == 9){
		mvwprintw(stdscr,i + 1,0,"Input error, please check(Y X):");
	}
	return 0;
}

int toAI(){
	AI   AIBase(sCols, sLines);
	AIBase.AISearch();
	
	return AIutil.AIsitting(sCols, sLines);
}

